<?php
namespace app\api\controller;

use app\api\service\JwtAuth;
use app\common\model\Users;
use think\facade\Db;
use think\facade\Request;
use app\api\validate\User as Userverify;
use app\api\validate\Declares;

class User extends Base
{
    /**
     * 控制器中间件 [登录、注册 不需要鉴权]
     * @var array
     */
    protected $middleware = [
        'app\api\middleware\Api' => ['except' => []],
    ];

    protected $uploadValidate = ['file' => [
        'fileSize' => 4 * 1024 * 1024,
        'fileExt'  => 'jpg,png,gif,jpeg'
    ]];

    protected $uploadfileValidate = ['file' => [
        'fileSize' => 4 * 1024 * 1024,
        'fileExt'  => 'txt,doc,xls,ppt,pdf,xls,docx,xlsx,doc'
    ]];

    public function index()
    {
        $user = Db::name('users')
            ->alias('u')
            ->leftJoin('users_type ut', 'u.type_id = ut.id')
            ->field('u.id,u.mobile,u.verifystatus,u.last_login_time,u.type_id,u.status,ut.name as type_name')
            ->where('u.id', $this->getUid())
            ->find();
        return $this->result($user, 1, '');
    }

    public function upload()
    {
        $file = request()->file('file');
        try {
            validate($this->uploadValidate)
                ->check(['file' => $file]);
            $savename = \think\facade\Filesystem::disk('public')->putFile('uploads', $file);
            // windows系统中路径反斜杠处理
            $savename = '/storage/'.str_replace('\\', '/', $savename);
            $this->result(['path'=>$savename], 1, '上传成功');
        } catch (think\exception\ValidateException $e) {
 
             $this->result([], 0, $e->getMessage());
        }

    }

    public function uploadfile()
    {
        $file = request()->file('file');
        try {
            validate($this->uploadfileValidate)
                ->check(['file' => $file]);
            $savename = \think\facade\Filesystem::disk('public')->putFile('uploads', $file);
            // windows系统中路径反斜杠处理
            $savename = '/storage/'.str_replace('\\', '/', $savename);
            $this->result(['path'=>$savename], 1, '上传成功');
        } catch (think\exception\ValidateException $e) {
             $this->result([], 0, $e->getMessage());
        }

    }


    /*个人认证*/
    public function personalverify(){
        $data = Request::only(['fullname','idcard','card1','card2']);
        try{
            validate(Userverify::class)->scene('personalverify')->check($data);
            
        }catch(\Exception $e){
             $this->result([], 0, '申请认证失败：'.$e->getMessage());
        }  
        $data['verifystatus'] = 1;
        $data['type_id'] = 1;
        Db::name('users')->where('id', $this->getUid())->update($data);
        if ($this->system['message_send_mail']) {
            //默认收件人为系统设置中的邮件
            $email = $this->system['email'];
            $title = '大同市知识产权公共服务平台提醒：您的网站有新的个人认证';
        
            $this->trySend($email,$title,$title);
        }
        $this->result([], 1, '申请认证成功');
    }

    /*企业认证*/
    public function businessverify(){
        $data = Request::only(['fullname','phone','card1','cname','ccode']);
        try{
            validate(Userverify::class)->scene('businessverify')->check($data);
            
        }catch(\Exception $e){
             $this->result([], 0, '申请认证失败：'.$e->getMessage());
        }

        $data['verifystatus'] = 1;
        $data['type_id'] = 2;

        Db::name('users')->where('id', $this->getUid())->update($data);
        if ($this->system['message_send_mail']) {
            //默认收件人为系统设置中的邮件
            $email = $this->system['email'];
            $title = '大同市知识产权公共服务平台提醒：您的网站有新的企业认证';
        
            $this->trySend($email,$title,$title);
        }
        $this->result([], 1, '申请认证成功');

    }

    /*模板列表*/
    public function downloadlist(){
        $list = Db::name('download')->field('id,title,images,download')->where('status', 1)->select();
        $this->result(['list'=>$list], 1, '');
    }

    /*商标类别列表*/
    public function brandlist(){
        $list = Db::name('brand')->field('id,title')->where('status', 1)->order('sort asc')->select();
        $this->result(['list'=>$list], 1, '');
    }

    /**/
    public function applybrand(){
        if (request()->isPost()) {
            $data = Request::only(['id','letter','brand_id','desc']);
            try{
                validate(Declares::class)->scene('applybrand')->check($data);
            }catch(\Exception $e){
                 $this->result([], 0, '申请商标认证失败：'.$e->getMessage());
            }
            $data['type'] = 0;
            $data['user_id'] = $this->getUid();
            $user = Db::name('users')->where('id',$data['user_id'])->value('type_id');
            $data['applicant'] = $user == 1 ? 0 : 1;
            if ($this->system['message_send_mail']) {
                //默认收件人为系统设置中的邮件
                $email = $this->system['email'];
                $title = '大同市知识产权公共服务平台提醒：您的网站有新的商标申请，请尽快处理';
            
                $this->trySend($email,$title,$title);
            }

            if(isset($data['id'])){
            	$decid = Db::name('declares')->where('user_id',$data['user_id'])->where('id',$data['id'])->value('id');
            	if($decid){
            		$data['update_time'] = time();
            		$res = Db::name('declares')->update($data);
            		if($res){
		                $this->result([], 1, '修改商标认证成功');
		            }else{
		                $this->result([], 0, '修改商标认证失败,请联系管理员');
		            }
            	}else{
            		 $this->result([], 0, '非法操作error');
            	}
            }else{
            	$data['create_time'] = $data['update_time'] = time();
            	$id = Db::name('declares')->insertGetId($data);
            	if($id){
	                $this->result([], 1, '申请商标认证成功');
	            }else{
	                $this->result([], 0, '申请商标认证失败,请联系管理员');
	            }
            }
        }else{
            $this->result([], 0, '非法请求');
        }
        
    }

    public function applypatent(){
        if (request()->isPost()) {
            $data = Request::only(['id','letter','techbook','desc']);
            try{
                validate(Declares::class)->scene('applypatent')->check($data);
            }catch(\Exception $e){
                 $this->result([], 0, '申请专利认证失败：'.$e->getMessage());
            }

            $data['type'] = 1;
            $data['user_id'] = $this->getUid();
            $user = Db::name('users')->where('id',$data['user_id'])->value('type_id');
            $data['applicant'] = $user == 1 ? 0 : 1;
            if ($this->system['message_send_mail']) {
                //默认收件人为系统设置中的邮件
                $email = $this->system['email'];
                $title = '大同市知识产权公共服务平台提醒：您的网站有新的专利申请，请尽快处理';
            
                $this->trySend($email,$title,$title);
            }



            if(isset($data['id'])){
            	$decid = Db::name('declares')->where('user_id',$data['user_id'])->where('id',$data['id'])->value('id');
            	if($decid){
            		$data['update_time'] = time();
            		$res = Db::name('declares')->update($data);
            		if($res){
		                $this->result([], 1, '修改专利认证成功');
		            }else{
		                $this->result([], 0, '修改专利认证失败,请联系管理员');
		            }
            	}else{
            		 $this->result([], 0, '非法操作error');
            	}
            }else{
            	$data['create_time'] = $data['update_time'] = time();
            	$id = Db::name('declares')->insertGetId($data);
            	if($id){
	                $this->result([], 1, '申请专利认证成功');
	            }else{
	                $this->result([], 0, '申请专利认证失败,请联系管理员');
	            }
            }

        }else{
            $this->result([], 0, '非法请求');
        }
        
    }


    public function applycopyright(){
        if (request()->isPost()) {
            $data = Request::only(['id','letter','techbook','pic','desc','is_public','show_time','show_preson','show_address','show_mean','show_process','show_use']);
            try{
                validate(Declares::class)->scene('applycopyright')->check($data);
            }catch(\Exception $e){
                 $this->result([], 0, '申请版权认证失败：'.$e->getMessage());
            }

            $data['type'] = 2;
            $data['user_id'] = $this->getUid();
            $user = Db::name('users')->where('id',$data['user_id'])->value('type_id');
            $data['applicant'] = $user == 1 ? 0 : 1;

            if ($this->system['message_send_mail']) {
                //默认收件人为系统设置中的邮件
                $email = $this->system['email'];
                $title = '大同市知识产权公共服务平台提醒：您的网站有新的版权申请，请尽快处理';
            
                $this->trySend($email,$title,$title);
            }


            if(isset($data['id'])){
            	$decid = Db::name('declares')->where('user_id',$data['user_id'])->where('id',$data['id'])->value('id');
            	if($decid){
            		$data['update_time'] = time();
            		$res = Db::name('declares')->update($data);
            		if($res){
		                $this->result([], 1, '修改版权认证成功');
		            }else{
		                $this->result([], 0, '修改版权认证失败,请联系管理员');
		            }
            	}else{
            		 $this->result([], 0, '非法操作error');
            	}
            }else{
            	$data['create_time'] = $data['update_time'] = time();
            	$id = Db::name('declares')->insertGetId($data);
            	if($id){
	                $this->result([], 1, '申请版权认证成功');
	            }else{
	                $this->result([], 0, '申请版权认证失败,请联系管理员');
	            }
            }
            
        }else{
            $this->result([], 0, '非法请求');
        }
        
    }



    public function getapplylist(){
        $user = Db::name('declares')->where('user_id', $this->getUid())->select();
        return $this->result($user, 1, '');
    }

    public function getapplyitem(){
        $id = request()->get('id/d');
        $info = Db::name('declares')->where('user_id',$this->getUid())->where('id',$id)->find();
        if(!$info['id']){
             $this->result([], 0, '非法请求');
        }
        $this->result(['detail'=>$info], 1, '');

    }

    public function deleteapplyitem(){
        $id = request()->get('id/d');
        $info = Db::name('declares')->where('user_id',$this->getUid())->where('id',$id)->find();
        if(!$info['id']){
             $this->result([], 0, '非法请求');
        }
        Db::name('declares')->where('id',$id)->delete();
        $this->result([], 1, '删除成功');
    }

    //维权
    public function sumbitwq(){
        if (request()->isPost()) {
              $user = Db::name('users')->where('id',$this->getUid())->field('fullname,mobile')->find();
              $data['name'] = $user['fullname'];
              $data['phone'] = $user['mobile'];
              $data['cate_id'] = 13;
              $data['create_time'] = $data['update_time'] = time();

              $data['title'] = '维权请求';
              $data['project_sku'] ='维权请求';
               $data['content'] ='维权请求';
              $id = Db::name('message')->insertGetId($data);
              if ($this->system['message_send_mail']) {
                //默认收件人为系统设置中的邮件
                $email = $this->system['email'];
                $title = '大同市知识产权公共服务平台提醒：您的网站有新的维权申请，请尽快处理';
            
                $this->trySend($email,$title,$title);
            }
              $this->result([], 1, '提交成功，等待工作人员与您联系，或者您可以直接拨打电话');
              
        }else{
               $this->result([], 0, '非法请求');
        }
    
    }

    /**快速购买**/
    public function submitapply(){
        if (request()->isPost()) {
            $data = Request::only(['project_sku','content']);
            $skuinfo = Db::name('projects_sku')->where('id',$data['project_sku'])->field('projects_id,specs_value_id,price')->find();
            if($skuinfo){
                $user = Db::name('users')->where('id',$this->getUid())->field('fullname,mobile')->find();
                $data['name'] = $user['fullname'];
                $data['phone'] = $user['mobile'];
                $data['cate_id'] = 13;
                $data['create_time'] = $data['update_time'] = time();

                $data['title'] = Db::name('projects')->where('id',$skuinfo['projects_id'])->value('title');
                $data['project_sku'] = \app\common\model\ProjectsSku::getSpecss($skuinfo['specs_value_id']);
                $id = Db::name('message')->insertGetId($data);
                if($id){
                    if ($this->system['message_send_mail']) {
                        //默认收件人为系统设置中的邮件
                        $email = $this->system['email'];
                        $title = '大同市知识产权公共服务平台提醒：您的网站有新的购买申请，请尽快处理';
                    
                        $this->trySend($email,$title,$title);
                    }
                    $this->result([], 1, '提交成功，我们将会尽快给您回电');
                }else{
                    $this->result([], 0, '提交失败，请联系管理员');
                }

            }else{
                $this->result([], 0, '项目属性sku未找到error');
            }

    
        }else{
            $this->result([], 0, '非法请求');
        }

    }

    /**询价**/
    public function submitmessage(){
        if (request()->isPost()) {
            $data = Request::only(['id']);
            $trademark = Db::name('trademark')->where('id',$data['id'])->find();
            if($trademark){
                $user = Db::name('users')->where('id',$this->getUid())->field('fullname,mobile')->find();
                $datas['name'] = $user['fullname'];
                $datas['phone'] = $user['mobile'];
                $datas['create_time'] = $datas['update_time'] = time();

                $datas['trademark_id'] = $data['id'];
             
                $id = Db::name('getmessage')->insertGetId($datas);
                if($id){
                    if ($this->system['message_send_mail']) {
                        //默认收件人为系统设置中的邮件
                        $email = $this->system['email'];
                        $title = '大同市知识产权公共服务平台提醒：您的网站有新的询价申请，请尽快处理';
                    
                        $this->trySend($email,$title,$title);
                    }
                    $this->result([], 1, '提交成功，我们将会尽快给您回电');
                }else{
                    $this->result([], 0, '提交失败，请联系管理员');
                }

            }else{
                $this->result([], 0, '商标未未找到error');
            }

    
        }else{
            $this->result([], 0, '非法请求');
        }

    }

    

    /**
     * @api {post} /User/editPwd 04、修改密码
     * @apiGroup User
     * @apiVersion 6.0.0
     * @apiDescription  修改会员密码，返回成功或失败提示

     * @apiParam (请求参数：) {string}     		token Token
     * @apiParam (请求参数：) {string}     		oldPassword 原密码
     * @apiParam (请求参数：) {string}     		newPassword 新密码

     * @apiSuccessExample {json} 成功示例
     * {"code":1,"msg":"密码修改成功","time":1563527107,"data":[]}
     * @apiErrorExample {json} 失败示例
     * {"code":0,"msg":"token已过期","time":1563527082,"data":[]}
     */
    public function editPwd(string $oldPassword, string $newPassword){
        // 密码长度不能低于6位
        if (strlen($newPassword) < 6) {
            $this->result([], 0, '密码长度不能低于6位');
        }

        // 查看原密码是否正确
        $user = Users::where('id', $this->getUid())
            ->where('password', md5($oldPassword))
            ->find();
        if (!$user) {
            $this->result([], 0, '原密码输入有误');
        }

        //更新信息
        $user = Users::find($this->getUid());
        $user->password = md5($newPassword);
        $user->save();
        $this->result([], 1, '密码修改成功');
    }

    /**
     * @api {post} /User/editInfo 05、修改信息
     * @apiGroup User
     * @apiVersion 6.0.0
     * @apiDescription  修改用户信息，返回成功或失败提示

     * @apiParam (请求参数：) {string}     		token Token
     * @apiParam (请求参数：) {string}     		sex 性别 [1男/0女]
     * @apiParam (请求参数：) {string}     		qq  qq
     * @apiParam (请求参数：) {string}     		mobile  手机号

     * @apiSuccessExample {json} 成功示例
     * {"code":0,"msg":"修改成功","time":1563507660,"data":[]}
     * @apiErrorExample {json} 失败示例
     * {"code":0,"msg":"token已过期","time":1563527082,"data":[]}
     */
    public function editInfo(){
        $data['sex']    = trim(Request::param("sex"));
        $data['qq']     = trim(Request::param("qq"));
        $data['mobile'] = trim(Request::param("mobile"));
        if ($data['mobile']) {
            // 不可和其他用户的一致
            $id = Users::
                where('mobile', $data['mobile'])
                ->where('id', '<>', $this->getUid())
                ->find();
            if ($id) {
                $this->result([], 0, '手机号已存在');
            }
        }
        // 更新信息
        Users::where('id', $this->getUid())
            ->update($data);
        $this->result([], 0, '修改成功');
    }

    /**
     * 获取用户id
     * @return mixed
     */
    protected function getUid(){
        $jwtAuth = JwtAuth::getInstance();
        return $jwtAuth->getUid();
    }

     private function trySend($email,$title,$content){
        //检查是否邮箱格式
        if (!is_email($email)) {
            return ['error' => 1, 'msg' => '邮箱码格式有误'];
        }
        $send = send_email($email, $title,$content);
        if ($send) {
            return ['error' => 0, 'msg' => '邮件发送成功！'];
        } else {
            return ['error' => 1, 'msg' => '邮件发送失败！'];
        }
    }
}
